package com.study.skywalking.api.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.study.skywalking.api.MyRestService;
import com.study.skywalking.component.RocketProduct;
import com.study.skywalking.dto.MyRestDTO;
import com.study.skywalking.dto.MyServerDTO;
import com.study.skywalking.entity.StudyServiceInfo;
import com.study.skywalking.service.IStudyServiceInfoService;
import com.study.skywalking.vo.MyServerVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhangbo on 2020/6/8.
 */
@Slf4j
@Component
@DubboService
public class MyRestServiceImpl implements MyRestService {


    @Autowired
    private IStudyServiceInfoService studyServiceInfoService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RocketProduct rocketProduct;

    @Value("${ROCKET.TOPIC:MyTopic}")
    private String topic;

    @Value("${ROCKET.TAGS:MyTags}")
    private String tags;


    @Override
    public MyRestDTO rest(MyServerVO restVO) {
        StudyServiceInfo studyServiceInfo = new StudyServiceInfo();
        studyServiceInfo.setServiceName(restVO.getServiceIp());
        studyServiceInfo.setServicePort(restVO.getServicePort());
        studyServiceInfo.setCreateTime(LocalDateTime.now());
        studyServiceInfoService.save(studyServiceInfo);
        MyRestDTO result = new MyRestDTO();
        result.setValue("id:" + studyServiceInfo.getId());
        return result;
    }


    @Override
    public MyServerDTO myServer() {
        List<StudyServiceInfo> resultList = studyServiceInfoService.list();
        if (resultList.isEmpty()) {
            return null;
        }
        MyServerDTO result = new MyServerDTO();
        BeanUtils.copyProperties(resultList.get(0), result);
        return result;
    }

    @Override
    public MyServerDTO testException() {
        throw new RuntimeException("测试异常");
    }


    @Override
    public String testRedis(String uid) {
        String testKey = stringRedisTemplate.opsForValue().get("testKey");
        if (StringUtils.isEmpty(testKey)) {
            stringRedisTemplate.opsForValue().set("testKey", uid);
            stringRedisTemplate.expire("testKey", 10, TimeUnit.SECONDS);
            return uid;
        }
        return testKey;
    }

    @Override
    public String sendMessage(List<String> messageList) {
        if (null == messageList || messageList.isEmpty()) {
            return "message is empty!";
        }
        int i = 0;
        for (String msg : messageList) {
            Message message = null;
            try {
                message = new Message(topic, tags, "key" + (i++), msg.getBytes(RemotingHelper.DEFAULT_CHARSET));
            } catch (UnsupportedEncodingException e) {
                log.error("编码转换异常：{}", e);
            }
            SendResult sendResult = rocketProduct.sendMessage(message);
            if (sendResult.getSendStatus().equals(SendStatus.SEND_OK)) {
                log.info("消息：{}，发送完成！", msg);
            } else {
                log.warn("消息：{}，发送失败！MQ返回状态：{}", msg, sendResult.getSendStatus());
            }
        }
        return "success";
    }


}
